import React, { useState, useEffect } from 'react';
import { CheckSSHKeys, GenerateSSHKeys, DeleteSSHKeys, ImportSSHKey } from '../../wailsjs/go/main/App';

const KeyManager = ({ onKeyStatusChange }) => {
  const [keyStatus, setKeyStatus] = useState({
    checked: false,
    exists: false,
    privateKeyPath: '',
    publicKeyPath: ''
  });

  const [status, setStatus] = useState({
    message: '',
    isError: false,
    loading: false
  });

  useEffect(() => {
    checkKeys();
  }, []);

  const checkKeys = async () => {
    try {
      setStatus({ message: '正在检查SSH密钥...', isError: false, loading: true });
      const result = await CheckSSHKeys(); // 取消注释
      // const result = { // 注释掉模拟数据
      //   privateKeyExists: false,
      //   publicKeyExists: false,
      //   privateKeyPath: '',
      //   publicKeyPath: ''
      // };
      setKeyStatus({
        checked: true,
        exists: result.privateKeyExists && result.publicKeyExists,
        privateKeyPath: result.privateKeyPath,
        publicKeyPath: result.publicKeyPath
      });
      onKeyStatusChange(result.privateKeyExists && result.publicKeyExists);
      setStatus({ message: '', isError: false, loading: false });
    } catch (error) {
      // Wails函数调用错误会进入catch块
      setStatus({ message: `检查SSH密钥时出错: ${error}`, isError: true, loading: false });
    }
  };

  const generateKeys = async () => {
    try {
      if (keyStatus.exists) {
        const confirmed = window.confirm('检测到已存在的SSH密钥，重新生成将覆盖现有密钥。是否继续？');
        if (!confirmed) {
          return;
        }
      }

      setStatus({ message: '正在生成SSH密钥...', isError: false, loading: true });

      // 增加超时保护（如10秒）
      const timeoutPromise = new Promise((_, reject) =>
        setTimeout(() => reject(new Error('生成密钥超时，请检查后端服务或系统权限')), 10000)
      );

      // 增加调试日志
      console.log('开始调用 GenerateSSHKeys');
      await Promise.race([
        GenerateSSHKeys(),
        timeoutPromise
      ]);
      console.log('GenerateSSHKeys 完成');

      await checkKeys();
      console.log('checkKeys 完成');
      setStatus({ message: 'SSH密钥生成成功', isError: false, loading: false });
    } catch (error) {
      console.error('生成密钥异常', error);
      setStatus({ message: `生成SSH密钥时出错: ${error.message || error}`, isError: true, loading: false });
    }
  };

  const deleteKeys = async () => {
    if (!window.confirm('确定要删除当前SSH密钥吗？此操作不可恢复。')) return;
    try { // 添加 try...catch
      setStatus({ message: '正在删除密钥...', isError: false, loading: true });
      const result = await DeleteSSHKeys(); // 取消注释
      // const result = { success: true }; // 注释掉模拟数据
      if (result.success) {
        setStatus({ message: '密钥已删除', isError: false, loading: false });
        await checkKeys(); // 重新检查密钥状态
      } else {
        setStatus({ message: '删除失败: ' + result.message, isError: true, loading: false });
      }
    } catch (error) {
      setStatus({ message: `删除密钥时出错: ${error}`, isError: true, loading: false });
    }
  };

  const importKey = async () => {
    try { // 添加 try...catch
      setStatus({ message: '正在导入密钥...', isError: false, loading: true });
      const result = await ImportSSHKey(); // 取消注释
      // const result = { success: true }; // 注释掉模拟数据
      if (result.success) {
        setStatus({ message: '密钥导入成功', isError: false, loading: false });
        await checkKeys(); // 重新检查密钥状态
      } else {
        // 如果用户取消选择文件，ImportSSHKey会返回 { success: false, message: "未选择文件" }
        // 只有在真正发生错误时才标记为isError
        const isActualError = result.message !== "未选择文件";
        setStatus({ message: '导入操作: ' + result.message, isError: isActualError, loading: false });
      }
    } catch (error) {
      setStatus({ message: `导入密钥时出错: ${error}`, isError: true, loading: false });
    }
  };

  return (
    <div className="key-manager">
      <h2>本地SSH密钥</h2>
      <div className="key-status">
        {keyStatus.checked && (
          <div className="status-info">
            {keyStatus.exists ? (
              <>
                <p>私钥路径: {keyStatus.privateKeyPath}</p>
                <p>公钥路径: {keyStatus.publicKeyPath}</p>
                <p className="warning-text">注意：重新生成密钥将覆盖现有密钥</p>
                <p className="info-text">提示：在 Mac 和 Linux 系统中，SSH 密钥默认存储在用户主目录的 .ssh 文件夹中</p>
              </>
            ) : (
              <>
                <p style={{ color: '#999' }}>未检测到密钥</p>
                <p className="info-text">提示：在 Mac 和 Linux 系统中，SSH 密钥默认存储在用户主目录的 .ssh 文件夹中</p>
              </>
            )}
          </div>
        )}
      </div>
      <div className="button-group">
        <button onClick={checkKeys} disabled={status.loading} className="secondary-button">
          <span role="img" aria-label="search">🔍</span> 检查密钥
        </button>
        <button onClick={generateKeys} disabled={status.loading} className="primary-button">
          <span role="img" aria-label="key">🔑</span> {keyStatus.exists ? '重新生成密钥' : '生成密钥'}
        </button>
        <button onClick={importKey} disabled={status.loading} className="secondary-button">
          <span role="img" aria-label="import">📥</span> 导入已有密钥
        </button>
        <button onClick={deleteKeys} disabled={status.loading || !keyStatus.exists} className="secondary-button">
          <span role="img" aria-label="delete">🗑️</span> 删除密钥
        </button>
      </div>
      {status.message && (
        <div className={`status-message ${status.isError ? 'error' : ''}`}>
          {status.message}
          {status.loading && <span className="loading-spinner"></span>}
        </div>
      )}
      <style jsx>{`
        .key-manager {
          padding: 20px;
        }
        .key-status {
          margin: 20px 0;
        }
        .status-info {
          background-color: #f8f9fa;
          padding: 15px;
          border-radius: 5px;
        }
        .warning-text {
          color: #dc3545;
          font-size: 0.9em;
          margin-top: 10px;
        }
        .info-text {
          color: #6c757d;
          font-size: 0.9em;
          margin-top: 10px;
          font-style: italic;
        }
        .button-group {
          display: flex;
          gap: 10px;
          margin: 20px 0;
        }
        .primary-button {
          background-color: #007bff;
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
        }
        .primary-button:disabled {
          background-color: #6c757d;
          cursor: not-allowed;
        }
        .secondary-button {
          background-color: #6c757d;
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
        }
        .secondary-button:disabled {
          background-color: #adb5bd;
          cursor: not-allowed;
        }
        .status-message {
          margin-top: 10px;
          padding: 10px;
          border-radius: 4px;
        }
        .status-message.error {
          background-color: #f8d7da;
          color: #721c24;
        }
        .loading-spinner {
          display: inline-block;
          width: 12px;
          height: 12px;
          border: 2px solid #f3f3f3;
          border-top: 2px solid #3498db;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-left: 10px;
        }
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
};

export default KeyManager;